<template>
  <div class="flow-list__wrapper">
    <!--翻页组件（真翻页）-->
    <table-wrap :all-list="actionList" ref='tableWrapRef' style="border-top: none">
      <div slot="search" class="fl">
        <el-button type="text"
                   class="primary_btn"
                   @click.stop="addAction"
                   size="mini">
          <i class="el-icon-plus"></i>{{$t('configLazyLoad.businessConfig.newAction')}}
        </el-button>
      </div>
      <el-table
        slot="table"
        size="mini"
        :stripe="true"
        border
        slot-scope="slotScope"
        :data="slotScope.current">
        <template v-for="item in tableHead">
          <el-table-column
            :prop="item.prop"
            :label="item.label"
            show-overflow-tooltip
          >
            <template scope="scope" >
              <!--文字样式有变化-->
              <span v-if="item.prop === 'actionFields'" :class="{'flow-table__warning': scope.row.actionFields.length === 0}">{{scope.row.actionFields.length ? $t('configLazyLoad.businessConfig.configured'): $t('configLazyLoad.businessConfig.noConfigured')}}</span>
              <!--操作-->
              <template v-else-if="item.prop === 'operate'">
                <span class="flow-table__button" @click.stop="detail(scope.row)">{{$t('public.intelDetails')}}</span>
                <span class="flow-table__button" @click.stop="copyAction(scope.row)">{{$t('configLazyLoad.businessConfig.copy')}}</span>
                <el-popover
                  placement="top"
                  v-model="scope.row.show"
                  trigger="click">
                  <div class="popover"> <i class="el-icon-warning flow-table__warning"></i>{{$t('configLazyLoad.businessConfig.businessdeleteTip1')}}</div>
                  <div style="text-align: right; margin: 0">
                    <el-button size="mini" @click="actionDelete(scope.row)">{{$t('public.delete')}}</el-button>
                    <el-button type="primary" size="mini" @click="scope.row.show = false">{{$t('public.cancel')}}</el-button>
                  </div>
                  <span class="flow-table__button flow-table__detele" slot="reference">{{$t('public.delete')}}</span>
                </el-popover>
              </template>
              <span v-else-if="item.prop === 'jumpToName'" :class="['flow-table__' + scope.row.status]">{{scope.row.jumpToName}}</span>
              <!--普通-->
              <template v-else>{{scope.row[item.prop]}}</template>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </table-wrap>
    <!--右侧滑出框-->
    <right-layout :visible="dialogObj.visible"
                  :title="dialogObj.title"
                  @close="close"
                  @save="save"
                  width="840px">
      <el-radio-group v-model="dialogObj.tab" class="radio" size="small">
        <el-radio-button label="actionInfo" name="actionInfo">{{$t('webchat.basicInfo')}}</el-radio-button>
        <el-radio-button label="actionLayout" name="actionLayout">{{$t('config.business.actionLayout')}}</el-radio-button>
      </el-radio-group>
      <!--表单信息通用组件（动作信息）-->
      <common-form :form="baseInfo"
                   v-show="dialogObj.tab === 'actionInfo'"
                   ref="form"
                   class="form"
                   label-position="top"
                   :formData="formData"
                   :rules="rules"
                   @selectChange = 'selectChange'
                   @typeChange='typeChange'
      >
        <div slot="jumpTo" class="prompt">
          {{$t('configLazyLoad.businessConfig.actionTip1')}}
        </div>
        <div slot="backFlag" class="prompt">
          {{$t('configLazyLoad.businessConfig.actionTip2')}}
        </div>
        <div slot="actionRole" class="prompt">
          {{$t('configLazyLoad.businessConfig.actionTip3')}}
        </div>
        <div slot="specific" class="prompt">
          {{$t('configLazyLoad.businessConfig.actionTip4')}}
        </div>
        <el-form-item :label="$t('configLazyLoad.businessConfig.actionTip5')">
          <el-radio-group v-model="dialogObj.tab" class="radio" size="small">
            <el-radio-button label="actionInfo" name="actionInfo">{{$t('webchat.basicInfo')}}</el-radio-button>
            <el-radio-button label="actionLayout" name="actionLayout">{{$t('config.business.actionLayout')}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </common-form>
      <!--动作界面设置-->
      <bus-drag :fieldsArr="currentAction.actionFields || []"
                class="action-drag"
                v-show="dialogObj.tab === 'actionLayout'"
                ref="actionDrag">
      </bus-drag>
    </right-layout>
    <!--复制动作弹框-->
    <el-dialog
      :title="copyDialog.title"
      :visible="copyDialog.visible"
      width="30%"
      @close="copyDialog.visible = false"
    >
      <span class="fl copy-label">{{$t('configLazyLoad.businessConfig.actionName')}}</span><el-input v-model="copyDialog.name" class="copy-input"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="copy">{{$t('public.confirm')}}</el-button>
        <el-button size="mini" @click="copyDialog.visible = false">{{$t('public.cancel')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import tableWrap from '../base/tableWrap'
  import {getObjectById} from '@/utils/workflowUtils'
  import rightLayout from '../base/rightLayout'
  import commonForm from '../base/commonForm'
  import busDrag from '../base/busDrag'
  import {deepClone} from '@/utils/m7Utils'
  export default {
    name: 'flowList',
    props: {
      currentStepInfo: {
        type: Object,
        default: function () {
          return []
        }
      }, // 当前步骤
      flowSteps: {
        type: Array,
        default: function () {
          return []
        } // 所有步骤
      }
    },
    data () {
      return {
        tableHead: [
          {prop: 'name', label: this.$t('configLazyLoad.businessConfig.actionName')},
          {prop: 'jumpToName', label: this.$t('configLazyLoad.businessConfig.actioneExecutionStep')},
          {prop: 'roleName', label: this.$t('configLazyLoad.businessConfig.performActionRole')},
          {prop: 'actionFields', label: this.$t('config.business.actionLayout')},
          {prop: 'operate', label: this.$t('public.operate')}
        ], // 表头
        actionList: [], // 所有list
        dialogObj: {
          visible: false,
          title: this.$t('configLazyLoad.businessConfig.newAction'),
          type: 'actionInfo',
          width: '840px'
        },
        copyDialog: {
          visible: false,
          title: '',
          name: ''
        },
        baseInfo: {
          specific: false, // 是否指定处理人
          name: '',
          actionAllow: 0,
          actionRole: [],
          actionQueue: [],
          jumpTo: '',
          QRCode: false,
          backFlag:"Y" //默认 步骤可以退回工单
        },
        formData: [ 
          {label: this.$t('configLazyLoad.businessConfig.actionName'), name: 'name', type: 'input'},
          {label: this.$t('configLazyLoad.businessConfig.actioneExecutionStep'), name: 'jumpTo', type: 'select', data: []},
          // {label: '退回', name: 'backFlag', type: 'switch',data:["Y","N"]},
          {label: this.$t('configLazyLoad.businessConfig.actionRole'), name: 'actionRole', type: 'radioSelect',data:[], data1: [{label:this.$t('config.agent.role'), value: 0}, {label: this.$t('public.queues'), value: 1}],multiple:true},
          {label: this.$t('configLazyLoad.businessConfig.designatedHandler'), name: 'specific', type: 'switch'},
          {label: this.$t('configLazyLoad.businessConfig.actionTip5'), name: 'QRCode', type: 'radioGroup', data: [{label: '是', value: true}, {label: '否', value: false}]}
        ],
        rules: {
          name: [
            {required: true, message: this.$t('validate.required'), trigger: 'change'},
            {
              validator: (rule, value, callback) => {
                if (value.length > 50) {
                  callback(new Error(this.$t('configLazyLoad.businessConfig.actionTip6')))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            }
          ],
          jumpTo: [
            {required: true, message: this.$t('validate.required'), trigger: 'change'}
          ],
          actionRole: [
            {required: true,validator: this.checkFrequency, trigger: 'change'}
          ]
        },
        currentAction: {},
        isAdd: true
      }
    },
    components: {
      tableWrap,
      rightLayout,
      commonForm,
      busDrag
    },
    watch: {
      'currentStepInfo.actions': {
        deep: true,
        handler: function () {
          this.initData()
        }
      }
    },
    methods: {
      checkFrequency(rule, value, callback) {
        if (this.baseInfo.actionRole.length === 0 && this.baseInfo.actionQueue.length === 0) {
          callback(new Error(this.$t('validate.required')))
        } else {
          callback()
        }
      },
      selectChange(data){
        /**
         * @Description 选择‘业务完成’ 和 ‘业务取消’时不展示退回开关
         * @params {Array} array: 只包含‘业务完成’ 和 ‘业务取消’数据的数组
         * @params {Boolean} isExist: 当前选择的是否是‘业务完成’ 和 ‘业务取消’
         * @params {Boolean} hasBack: formData中是否有了back开关，没有才插入
         */
        let array = [];
        if(data.name == 'jumpTo'){
          //筛选出‘业务完成’ 和 ‘业务取消’ 的数据
          array = this.formData.filter(item=>{
            return item.name == data.name
          })[0].data.filter(val=>{
            return val.label == this.$t('public.complete') || val.label == this.$t('public.bussinessCancel')
          })
          //查看当前下拉框选的选项是否是‘业务完成’ 或者 ‘业务取消’
          let isExist = array.some(item=>{
            return item.value == data.value
          })
          if(isExist){
            //不展示退回开关
            this.formData = this.formData.filter(item=>{
              return item.name != 'backFlag'
            })
          }else{
            //展示退回开关
            let hasBack = this.formData.some(item=>{
              return item.name == 'backFlag'
            })
            if(!hasBack){
              //避免重复插入
              let obj = {label:this.$t('business.return') , name: 'backFlag', type: 'switch',data:["Y","N"]};
              this.formData.splice(2,0,obj)
            }
          }
        }
      },
      typeChange(val){
        this.baseInfo.actionRole = []
        this.baseInfo.actionQueue = []
        if(val===1){
          this.$store.dispatch('getCache', {type: 'businessQueue'}).then((queue) => {
            if(queue) {
              let queueArr = queue.map((item) => {
                return {label: item.DisplayName, value: item._id}
              })
              this.formData.forEach((item) => {
                if (item.name === 'actionRole') {
                  item.data = queueArr
                }
              })
            }
          })
        } else {
          this.$store.dispatch('getCache', {type: 'roles'}).then((roles) => {
            let roleArr = roles.map((item) => {
              return {label: item.display_name, value: item._id}
            })
            roleArr.push({label: this.$t('business.businessCreate'), value: 'busCreateUser'})
            this.formData.forEach((item) => {
              if (item.name === 'actionRole') {
                  item.data = roleArr
              }
            })
          })
        }
      },
      // 获取工单列表
      initData () {
        Promise.all([
          this.$store.dispatch('getCache', { type: 'roles' }),
          this.$store.dispatch('getDicCache', { type: 'businessQueue'})
        ]).then(([roles, businessQueue]) => {
          // 获取除当前步骤以外的工单步骤
          let stepsArr = this.flowSteps.map((item) => {
            return {label: item.name, value: item._id}
          }).filter((item) => {
            return item.value !== this.currentStepInfo._id
          })
          let roleArr = roles.map((item) => {
            return {label: item.display_name, value: item._id}
          })
          roleArr.push({label: this.$t('business.businessCreate'), value: 'busCreateUser'})
          this.formData.forEach((item) => {
            if (item.name === 'jumpTo') {
              item.data = stepsArr
            } else if (item.name === 'actionRole') {
                item.data = roleArr
            }
          })
          this.actionList = this.currentStepInfo.actions.map(({_id, QRCode, name, jumpTo, specific, actionRole,actionQueue,actionAllow, actionFields,backFlag}, index) => {
            let step = getObjectById(this.flowSteps, jumpTo) || {}
            let jumpToName = step.name
            let status = step.systemFn
            let roleName = ''
            let roleNameList = []
            // 判断角色or技能组表格内展示
            if(actionRole.length>0) {
              //兼容老数据，之前是字符串
              if(!Array.isArray(actionRole)){
                actionRole = [actionRole]
              }
              actionRole.forEach(item=>{
                if (item === 'busCreateUser') {
                  roleNameList.push(this.$t('business.businessCreate'))
                }else{
                  roleNameList.push((getObjectById(roles, item) || {}).display_name)
                }
              })
              roleName = roleNameList.join(',')
            } else {
              if(businessQueue && businessQueue.data) {
                actionQueue.forEach(item=>{
                  roleNameList.push((getObjectById(businessQueue.data, item) || {}).DisplayName)
                })
                roleName = roleNameList.join(',')
              }
            }
            actionFields = actionFields || []
            return {_id, QRCode, name, jumpToName, status, roleName, specific, actionFields, show: false, actionRole,actionQueue,actionAllow, jumpTo, index, backFlag}
          }).reverse()
          this.$refs.tableWrapRef.init(this.isAdd)
        })
      },
      /*
      * 动作详情
      */
      detail (data) {
        this.isAdd = false
        this.dialogObj = {
          visible: true,
          title: this.$t('configLazyLoad.businessConfig.editAction'),
          tab: 'actionInfo',
          type: 'edit'
        }
        this.$store.commit('flowConfig/CHANGE_CURRENT_INDEX', {currentActionIndex: data.index})
        this.currentAction = data
        this.$nextTick(() => {
          this.$refs.actionDrag.initData()
          this.$refs.form.clearValidate()
          for (let i in this.baseInfo) {
            this.baseInfo[i] = this.currentAction[i] || ''
          }
          if (!this.baseInfo.specific) {
            this.baseInfo.specific = false
          }
          if (!this.baseInfo.QRCode) {
            this.baseInfo.QRCode = false
          }
          if(!this.baseInfo.backFlag){
            this.baseInfo.backFlag = "Y"
          }
          if(!this.baseInfo.actionAllow){
            this.baseInfo.actionAllow = 0
          }
          // 角色和技能组数据
          Promise.all([
            this.$store.dispatch('getCache', { type: 'roles' }),
            this.$store.dispatch('getDicCache', { type: 'businessQueue'})
          ]).then(([roles, businessQueue]) => {
            let roleArr = roles.map((item) => {
              return {label: item.display_name, value: item._id}
            })
            roleArr.push({label: this.$t('business.businessCreate'), value: 'busCreateUser'})
            let queueArr = []
            if(businessQueue && businessQueue.data) {
              queueArr = businessQueue.data.map((item) => {
                return {label: item.DisplayName, value: item._id}
              })
            }
            this.formData.forEach((item) => {
              if (item.name === 'actionRole') {
                if(this.baseInfo.actionAllow === 1) {
                  item.data = queueArr
                } else {
                  item.data = roleArr
                }
              }
            })
          })
          //点击详情进入动作编辑时，要查看当前动作是否是‘业务完成’或者‘业务取消’
          this.selectChange({name:'jumpTo',value:data.jumpTo})
        })
      },
      copyAction (data) {
        this.copyDialog.visible = true
        this.currentAction = data
        this.copyDialog.name = ''
        this.copyDialog.title = this.$t('configLazyLoad.businessConfig.copyAction')+`(${data.name})`
      },
      /*
      * 复制动作
      * */
      copy () {
        if (!this.copyDialog.name) {
          this.$message.error(this.$t('configLazyLoad.businessConfig.actionNameRequired'))
          return
        }
        this.$store.dispatch('copyBusinessStepAction', {flow_id: this.currentStepInfo.flow_id, _id: this.currentStepInfo._id, actionId: this.currentAction._id, name: this.copyDialog.name}).then((res) => {
          if (res.success) {
            this.$message.success(this.$t('config.business.copySuccess'))
            this.copyDialog.visible = false
            this.$store.commit('flowConfig/UPDATE_FLOW_ACTION', {type: 'add', data: res.data})
          }
        })
      },
      /*
      * 添加动作
      * */
      addAction () {
        this.isAdd = true
        this.dialogObj = {
          visible: true,
          title: this.$t('configLazyLoad.businessConfig.newAction'),
          tab: 'actionInfo',
          type: 'add'
        }
        this.baseInfo.actionAllow = 0
        this.currentAction = {}
        this.$refs.form.reset()
        this.baseInfo.specific = false;
        this.baseInfo.backFlag = "Y"
        this.$nextTick(() => {
          this.$refs.actionDrag.initData()
        })
      },
      /*
      * 动作删除
      * */
      actionDelete (data) {
        this.$store.dispatch('deleteBusinessStepAction', {flow_id: this.currentStepInfo.flow_id, _id: this.currentStepInfo._id, actionId: data._id}).then((res) => {
          if (res.success) {
            this.$message.success(this.$t('config.channel.deleteSuccess'))
            this.$store.commit('flowConfig/UPDATE_FLOW_ACTION', {type: 'delete', data: data.index})
          }
        })
      },
      /*
      * 关闭弹框
      * */
      close () {
        this.dialogObj.visible = false
      },
      /*
      * 保存动作信息
      * */
      save () {
        let data = this.$refs.form.submit()
        if (!data.success) {
          this.$message.error(this.$t('configLazyLoad.businessConfig.actionTip7'))
          return
        }
        // 基本信息
        let form = deepClone(data.data)
        if (form.actionAllow === 1) {
          form.actionRole = []
        } else{
          form.actionQueue = []
        }
        console.log(form,'form')
        // // 动作界面
        let actionFields = this.$refs.actionDrag.submit() || []
        form.actionFields = actionFields
        // 添加
        if (this.dialogObj.type === 'add') {
          form._id = this.currentStepInfo._id // 步骤id
          form.flow_id = this.currentStepInfo.flow_id
          this.$store.dispatch('addBusinessStepAction', form).then((res) => {
            if (res.success) {
              this.$message.success(this.$t('configLazyLoad.businessConfig.actionTip8'))
              this.dialogObj.visible = false
              this.$store.commit('flowConfig/UPDATE_FLOW_ACTION', {type: 'add', data: res.data})
            }
          })
        } else if (this.dialogObj.type === 'edit') {
          // 编辑
          let updateForm = {flow_id: this.currentStepInfo.flow_id, _id: this.currentStepInfo._id, actionId: this.currentAction._id, update: form}
          this.$store.dispatch('udpateBusinessStepAction', updateForm).then((res) => {
            if (res.success) {
              this.dialogObj.visible = false
              this.$message.success(this.$t('monitor.saveSuccess'))
              this.$store.commit('flowConfig/UPDATE_FLOW_ACTION', {type: 'update', data: form})
            }
          })
        }
      }
    },
    beforeMount () {

    }
  }
</script>

<style scoped lang='stylus'>
  @import "../../../../../assets/common.styl"
  .flow-list__wrapper
    height 100%
    overflow-y auto
    box-sizing border-box
  .flow-table__button
    color $c-main
    display inline-block
    padding-right:10px
    cursor pointer
  .flow-table__warning
    color $cf-color0
  .flow-table__cancel
    color $c-pink
  .flow-table__complete
    color $cf-color2
  .flow-table__detele
    color $c-pink
  .form
    width 500px
    padding 20px 0
  .action-drag
    padding 20px 0
  .copy-input
    width calc(100% - 80px)
  .copy-label
    padding 5px 5px 0 0
  .popover
    font-size 12px
    padding-bottom 15px
    i
      font-size 16px
      margin-right 5px
  .prompt
    color $c-prompt
    font-size 12px
    line-height 16px
</style>
